"use client";

import { toggleRole } from "@/app/actions/user_action";
import { useUserStore } from "@/store/userStore";
import { Button, Form, Modal, Radio } from "antd";
import { useState } from "react";

export default function SwitchRole() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = async () => {
    const val = form.getFieldsValue();
    const result = await toggleRole({
        ...val,
        id:userInfo?.id
    })
    if(result.data){
        window.location.href = '/admin'
    }
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const [userInfo] = useUserStore((state) => [state.user]);
  return (
    <div>
      <Button
        type="text"
        onClick={() => {
          showModal();
          form.setFieldValue('role', userInfo?.currentRole);
        }}
      >
        切换角色
      </Button>
      <Modal
        title="切换角色"
        onOk={handleOk}
        open={isModalOpen}
        onCancel={handleCancel}
      >
        <Form form={form}>
          <Form.Item label="" name='role'>
            <Radio.Group >
              {userInfo?.roles.map((it) => {
                return (
                  <Radio key={it.id} value={it.id}>
                    {it.name}
                  </Radio>
                );
              })}
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
